<?php

include('../../include/functions.inc.php');
include( '../../include/FileReader.php' );
include( '../../include/CSVReader.php' );
if (!isEmpty(getParam('operation'))) {
    switch (getParam('operation')) {
        case 'refresh':
            loadCareer($db);
            break;
        case 's':
            save($db, $user);
            break;
        case 'prev':
            prevAssign($db, $user);
            break;
        case 'stud':
            listStudents();
            break;
    }
}

function prevAssign($db, $user) {
    $prev = findTeacherAssigns($db, getParam("ID"), $user, getParam("CODE"));
    $data = array('ST' => 1);
    if ($prev) {
        $data = array('ST' => 0, 'ERROR' => 'El Catedratico ya tiene asignado este curso!');
    }
    $_SESSION['pack'] = serialize($data);
    header('Location: ../../include/transport.php');
}

function save($db, $user) {

    $teacher = getParam('ID');
    $scores = getRowsToInsert();

    $teacherAssign = $db->query_select("cllg_teacher_assign", "ID=" . sqlValue(getParam("CURSO"), "int"));
    $teacherAssign = $teacherAssign[0];

    $sqlStudentAssign = "SELECT b.ID FROM cllg_student_assign a,cllg_assign_detail b
            WHERE a.ID=b.FK_ASSIGN AND a.FK_CYCLE=" . sqlValue(getParam("CYCLE"), "int");
    $notaMin = getParam("MINIMA");
    foreach ($scores as $nota) {
        $wStud = " AND a.FK_STUDENT=" . sqlValue($nota[0], "int") .
                " AND b.FK_COURSE=" . sqlValue($teacherAssign["FK_COURSE"], "int") .
                " AND b.SECTION=" . sqlValue($teacherAssign["SECTION"], "text");

        $r = $db->queryToArray($sqlStudentAssign . $wStud);
        $r = $r[0];
        $aprobada = $nota[1] > $notaMin ? 1 : 0;
        $db->query_update("cllg_assign_detail", array("SCORE" => sqlValue($nota[1], "double"), "MIN_SCORE" => sqlValue($notaMin, "double"), "APROVED" => $aprobada), sprintf("ID=%s",$r['ID']));
    }
    $total = count($scores);
    $msg = "Se cargaron notas de $total Alumnos!";
    echo $msg;
}

?>